"""
HR端演示模式API路由
移除登录验证，使用虚拟数据进行演示
"""

from fastapi import APIRouter, HTTPException, status, Query
from typing import List, Optional
import json
from datetime import datetime

from ...demo_data_loader import demo_loader

router = APIRouter(prefix="/demo/hr", tags=["HR演示模式"])

@router.get("/dashboard/stats")
async def get_recruitment_statistics():
    """获取招聘统计数据"""
    try:
        stats = await demo_loader.get_recruitment_stats()
        return {
            "status": "success",
            "data": stats
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取统计数据失败: {str(e)}"
        )

@router.get("/jobs")
async def get_job_positions(
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数"),
    category: Optional[str] = Query(None, description="职位类别"),
    location: Optional[str] = Query(None, description="工作地点"),
    salary_min: Optional[int] = Query(None, description="最低薪资"),
    salary_max: Optional[int] = Query(None, description="最高薪资")
):
    """获取职位列表"""
    try:
        jobs = await demo_loader.get_jobs(
            skip=skip,
            limit=limit,
            category=category,
            location=location,
            salary_min=salary_min,
            salary_max=salary_max
        )
        
        return {
            "status": "success",
            "data": jobs,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(jobs)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取职位列表失败: {str(e)}"
        )

@router.get("/jobs/{job_id}")
async def get_job_position(job_id: str):
    """获取职位详情"""
    try:
        job = await demo_loader.get_job_by_id(job_id)
        if not job:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="职位不存在"
            )
        
        return {
            "status": "success",
            "data": job
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取职位详情失败: {str(e)}"
        )

@router.get("/jobs/search")
async def search_jobs(
    q: str = Query(..., description="搜索关键词"),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数")
):
    """搜索职位"""
    try:
        jobs = await demo_loader.search_jobs(q, skip=skip, limit=limit)
        
        return {
            "status": "success",
            "data": jobs,
            "query": q,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(jobs)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"搜索职位失败: {str(e)}"
        )

@router.get("/candidates")
async def get_candidates(
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数"),
    category: Optional[str] = Query(None, description="候选人类别"),
    location: Optional[str] = Query(None, description="期望工作地点"),
    experience_min: Optional[int] = Query(None, description="最少工作经验"),
    experience_max: Optional[int] = Query(None, description="最多工作经验")
):
    """获取候选人列表"""
    try:
        candidates = await demo_loader.get_candidates(
            skip=skip,
            limit=limit,
            category=category,
            location=location,
            experience_min=experience_min,
            experience_max=experience_max
        )
        
        return {
            "status": "success",
            "data": candidates,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(candidates)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取候选人列表失败: {str(e)}"
        )

@router.get("/candidates/{candidate_id}")
async def get_candidate_detail(candidate_id: str):
    """获取候选人详情"""
    try:
        candidate = await demo_loader.get_candidate_by_id(candidate_id)
        if not candidate:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="候选人不存在"
            )
        
        return {
            "status": "success",
            "data": candidate
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取候选人详情失败: {str(e)}"
        )

@router.get("/candidates/search")
async def search_candidates(
    q: str = Query(..., description="搜索关键词"),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数")
):
    """搜索候选人"""
    try:
        candidates = await demo_loader.search_candidates(q, skip=skip, limit=limit)
        
        return {
            "status": "success",
            "data": candidates,
            "query": q,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(candidates)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"搜索候选人失败: {str(e)}"
        )

@router.get("/candidates/{candidate_id}/analysis")
async def analyze_candidate_resume(candidate_id: str):
    """分析候选人简历"""
    try:
        analysis = await demo_loader.analyze_resume(candidate_id)
        if not analysis:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="候选人不存在"
            )
        
        return {
            "status": "success",
            "data": analysis
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"分析简历失败: {str(e)}"
        )

@router.post("/resumes/{resume_id}/analyze")
async def analyze_resume_by_id(resume_id: str):
    """通过简历ID分析简历（演示模式）"""
    try:
        # 演示模式：返回模拟的智能分析结果
        # 这展示了Data Layer + RAG Engine的完整工作流程
        
        # 检查简历是否存在（基于之前存储的数据）
        known_resume_ids = [
            "d078ac02-5205-46ad-8e19-39eabe12498f",  # 张三
            "5bc0e0b2-0a63-4a27-bdf7-4f0df4059963",  # 李四  
            "0a7e1e6d-3713-4a62-9c14-9d7c6c483caf",  # 王五
            "189d859f-b407-4b50-909a-a47b1d8df274",  # 最新存储的
            "a164b1e3-dcf5-4ef3-96a6-1bdfa9db8719"   # 另一个存储的
        ]
        
        if resume_id not in known_resume_ids:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="简历不存在"
            )
        
        # 模拟RAG Engine的智能分析结果
        mock_analysis = {
            "resume_id": resume_id,
            "analysis": {
                "summary": "这是一位经验丰富的Python工程师，具有扎实的技术基础和丰富的项目经验。",
                "technical_skills": {
                    "programming_languages": ["Python", "JavaScript", "SQL"],
                    "frameworks": ["Django", "Flask", "React"],
                    "tools": ["Docker", "Redis", "PostgreSQL", "Git"],
                    "skill_level": "高级"
                },
                "experience_analysis": {
                    "total_years": "5年",
                    "key_projects": [
                        "电商平台后端系统开发",
                        "微服务架构设计与实现",
                        "数据分析平台建设"
                    ],
                    "leadership_experience": "有团队管理经验"
                },
                "strengths": [
                    "技术能力突出，掌握多项核心技术",
                    "项目经验丰富，有完整的系统开发经历",
                    "学习能力强，能快速适应新技术",
                    "有良好的团队协作精神"
                ],
                "areas_for_improvement": [
                    "可以进一步加强算法和数据结构知识",
                    "建议学习云原生和容器编排技术",
                    "可以补充前端框架的深度理解"
                ],
                "match_score": 92,
                "recommendation": "强烈推荐，该候选人技能匹配度高，经验丰富，建议优先面试。"
            },
            "confidence": 0.92,
            "processed_by": ["data_layer", "rag_engine", "ai_agents"],
            "analyzed_at": datetime.now().isoformat()
        }
        
        return {
            "status": "success",
            "data": mock_analysis
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"分析简历失败: {str(e)}"
        )

@router.get("/jobs/{job_id}/matched-candidates")
async def get_matched_candidates_for_job(
    job_id: str,
    limit: int = Query(10, description="返回的候选人数量")
):
    """获取岗位匹配的候选人"""
    try:
        matched_candidates = await demo_loader.match_candidates_for_job(job_id, limit=limit)
        
        return {
            "status": "success",
            "data": matched_candidates,
            "job_id": job_id,
            "total_matched": len(matched_candidates)
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取匹配候选人失败: {str(e)}"
        )

@router.post("/candidates/batch-analysis")
async def batch_analyze_candidates(candidate_ids: List[str]):
    """批量分析候选人"""
    try:
        analyses = []
        for candidate_id in candidate_ids:
            analysis = await demo_loader.analyze_resume(candidate_id)
            if analysis:
                analyses.append(analysis)
        
        return {
            "status": "success",
            "data": analyses,
            "total_analyzed": len(analyses)
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"批量分析失败: {str(e)}"
        )

@router.get("/categories")
async def get_job_categories():
    """获取职位类别统计"""
    try:
        categories = await demo_loader.get_job_categories()
        
        return {
            "status": "success",
            "data": categories
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取职位类别失败: {str(e)}"
        )

@router.get("/analytics/summary")
async def get_analytics_summary():
    """获取分析汇总数据"""
    try:
        stats = await demo_loader.get_recruitment_stats()
        
        # 生成一些分析数据
        analysis_summary = {
            "total_resumes_analyzed": stats["total_candidates"],
            "avg_candidate_score": 78.5,
            "top_skills": ["Python", "JavaScript", "项目管理", "数据分析", "团队协作"],
            "popular_locations": ["北京", "上海", "深圳", "杭州", "广州"],
            "experience_distribution": {
                "0-2年": 25,
                "3-5年": 35,
                "6-8年": 25,
                "9年以上": 15
            },
            "monthly_trends": [
                {"month": "1月", "applications": 120},
                {"month": "2月", "applications": 135},
                {"month": "3月", "applications": 180},
                {"month": "4月", "applications": 165},
                {"month": "5月", "applications": 195}
            ]
        }
        
        return {
            "status": "success",
            "data": analysis_summary
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取分析汇总失败: {str(e)}"
        )